#!/bin/bash
DIR_PATH="./firmware"

num_args=$#
current_path=$PWD
complite_single_param=""
complite_show_details=""
complite_ignore_packages=""
create_tag_flag=0
create_deb_flag=0
ignore_packages=0
ignore_packages_array=() #("rcl_logging_spdlog" "rcutils")

result=0
clear 

adjust_swap() {
    local target_swap_gb=8  # 目标 swap 大小（GB）
    local current_swap_gb=$(free -h | awk '/Swap/ {gsub(/[^0-9.]/,"",$2); print $2}')

    if [ $(echo "$current_swap_gb < $target_swap_gb" | bc) -eq 1 ]; then
        echo -e "\033[35m#当前 swap 大小: ${current_swap_gb}GB（不足 ${target_swap_gb}GB），正在调整...\033[0m"

        sudo swapoff -a 2>/dev/null

        sudo fallocate -l ${target_swap_gb}G /swapfile >/dev/null 2>&1 && \
        sudo chmod 600 /swapfile >/dev/null 2>&1 && \
        sudo mkswap /swapfile >/dev/null 2>&1 && \
        sudo swapon /swapfile >/dev/null 2>&1

        # grep -q "/swapfile" /etc/fstab || \
        # echo "/swapfile none swap sw 0 0" | sudo tee -a /etc/fstab

        echo -e "\033[35m#swap 已调整为 ${target_swap_gb}GB\033[0m"
    fi
}

complite_firmware() {
    adjust_swap
    
    # export LD_LIBRARY_PATH="$current_path/firmware/lgimRobot/lib:$LD_LIBRARY_PATH"
    ulimit -Sv 6000000

    echo "正在编译..."
    #-DCMAKE_CXX_FLAGS="-w" \
    colcon build $complite_single_param \
      --build-base $DIR_PATH/build \
      --install-base $DIR_PATH/lgimRobot \
      --cmake-force-configure \
      --merge-install \
      --allow-overriding rcl_logging_spdlog \
        velocity_controllers \
        hardware_interface \
        controller_manager \
        ros2controlcli \
        joint_state_broadcaster \
        forward_command_controller \
        rcutils \
        controller_interface \
      --cmake-args \
        -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_SKIP_RPATH=FALSE \
      $complite_show_details \
      $complite_ignore_packages

    result=$?
}

run_complite() {
    rm ./log -rf
    
    # echo -e "\033[1;31m\n\n⚠️ 重要提示：首次编译或整体清理后 ('-c')，请务必使用 '-a' 参数执行一次完整编译！\n\n\033[0m"

    if [ $ignore_packages -eq 1 ]; then
        complite_ignore_packages="--packages-ignore"
        for package in "${ignore_packages_array[@]}"; do
            complite_ignore_packages="$complite_ignore_packages $package"
        done
        echo "Add ignore package command '$complite_ignore_packages'"
    fi

    complite_firmware
    
    if [ $result -eq 0 ]; then
        echo "编译成功！"

        if [ $ignore_packages -eq 0 ]; then 
            lib_path=$DIR_PATH/lgimRobot/lib
            ros_distro=${ROS_DISTRO}
            for package in "${ignore_packages_array[@]}"; do
                libpackage=$lib_path/"lib$package.so"
                if [ -f "$libpackage" ]; then
                    echo "找到库文件: $libpackage，正在拷贝到 /opt/ros/$ros_distro/lib"
                    sudo cp "$libpackage" /opt/ros/$ros_distro/lib/
                else
                    echo "库文件未找到: $libpackage"
                fi 
            done
        fi

        verion_head_path="$DIR_PATH/lgimRobot/include/firmware/firmware"

        hash=`cat $verion_head_path/ver.h | grep "hash" | sed 's/"//g;s/=/ /g;s/;//g' | awk '{print $4}'`
        branch=`cat $verion_head_path/ver.h | grep "branch" | sed 's/"//g;s/=/ /g;s/;//g' | awk '{print $4}'`
        tag=`cat $verion_head_path/ver.h | grep "tag" | sed 's/"//g;s/=/ /g;s/;//g' | awk '{print $4}'`
        echo "[Tools]" "$tag"-"$branch"-"$hash"

        if [ $create_tag_flag -gt 0 ]; then
            echo -n "正在生成压缩包..."
            cd $DIR_PATH
            tar -zcvf lgimRobot.tar.gz lgimRobot > /dev/null
            echo "完成"
        elif [ $create_deb_flag -gt 0 ]; then  
            echo "正在生成deb包..."
            PACKAGE_NAME="firmware"
            VERSION=${tag#V}
            WORK_DIR=$DIR_PATH/firmware
            SRC_DIR=$DIR_PATH/lgimRobot
            DEST_DIR="opt/ros/humble"
             
            # 创建工作目录
            mkdir -p "$WORK_DIR/DEBIAN"
            mkdir -p "$WORK_DIR/$DEST_DIR"
             
            # 复制文件
            cp -r "$SRC_DIR"/* "$WORK_DIR/$DEST_DIR/"
             
            # 创建 control 文件
            cat <<EOF > "$WORK_DIR/DEBIAN/control"
Package: $PACKAGE_NAME
Version: $VERSION
Section: custom
Priority: optional
Architecture: all
Maintainer: haibo <haibo.yang@lgmgim.cn>
Description: A custom package for lgimRobot to be installed in /opt/ros/humble/
EOF
            # 构建 .deb 包
            dpkg-deb --build "$WORK_DIR"
            
            mv "$DIR_PATH/firmware.deb" "$DIR_PATH/${PACKAGE_NAME}_${VERSION}.deb"
            rm $WORK_DIR -rf
        else
            echo "未启用任何生成标志"
        fi
    else
        echo "编译失败！ ($result)"
        exit 1  
    fi

}

clean() {
    echo "正在清理工作空间..."
    rm $DIR_PATH/build $DIR_PATH/lgimRobot ./log -rf
}

usage()
{
   echo "Usage: $0 [ -c ] [ -s package ] [ -t ] [ -e ] [ -a ]"
   echo ""
   echo "-c: 清理编译目录"
   echo "-s: 编译单个包 xxx"
   echo "-a: 编译所有的包（仅首次和清理后使用）, -- rcutils, rcl_logging_spdlog"
   echo "-h: 帮助"
   echo "-d: 编译时显示完整信息"
   echo "-e: 生成deb安装包"
   echo "-t: 生成tar安装包"

   echo "正常编译时, 使用agv_build编译完整包,使用agv_build -s编译单个包！"
}

while getopts ":s:adetch" opt; do
    case ${opt} in
        c )
            clean
            exit 0
            ;;
        s )
            echo -e "\033[31m#complite package: $OPTARG\033[0m" 
            complite_single_param="--packages-select $OPTARG"
            ;;
        d )
            echo -e "\033[31m#complite show details\033[0m"
            complite_show_details="--event-handlers console_cohesion+"
            ;;
        t )
            echo -e  "\033[0m#create tar\033[0m"
            create_tag_flag=1
            ;;
        e )
            create_deb_flag=1
            ;;
        a )
            ignore_packages=0
            ;;
        h )
            usage
            exit 0
            ;;
        \?)
            echo "Usage: $0 [-c | -s xxx | -t]" >&2
            exit 1
            ;;
        :)
            echo "Option -$OPTARG requires an argument." >&2
            echo "Usage: $0 [-c | -s xxx | -t]" >&2
            exit 1
            ;;
    esac
done

if [ ! -d "$DIR_PATH" ]; then
  mkdir -p "$DIR_PATH"
  if [ $? -eq 0 ]; then
    echo "创建: $DIR_PATH"
  else
    echo "创建失败: $DIR_PATH"
    exit 1
  fi
fi

run_complite
